//
//  NSURL+YFExtension.m
//  project
//
//  Created by yefei on 2019/4/10.
//  Copyright © 2019 健健. All rights reserved.
//

#import "NSURL+YFExtension.h"
#import <AVFoundation/AVFoundation.h>

@implementation NSURL (YFExtension)


/**
 压缩视频

 @param completion 压缩完成回调
 */
- (void)compressVideoCompletion:(void(^)(NSURL *outputURL, BOOL isSuccess))completion
{
    
    NSLog(@"压缩前大小：%f", self.videoSize);
    // 创建视频输出路径
    NSURL *outputVideoURL;
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名，以免重复，在测试的时候其实可以判断文件是否存在若存在，则删除，重新生成文件即可
    [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
    outputVideoURL = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]]];
    
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:self options:nil];
    AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetMediumQuality];
    session.outputURL = outputVideoURL;
    session.outputFileType = AVFileTypeMPEG4;
    session.shouldOptimizeForNetworkUse = YES;
    [session exportAsynchronouslyWithCompletionHandler:^{
       
        switch (session.status) {
            case AVAssetExportSessionStatusCancelled:
                LKLog(@"AVAssetExportSessionStatusCancelled");
                if (completion) {
                    completion(nil, NO);
                }
                break;
            case AVAssetExportSessionStatusFailed:
                LKLog(@"AVAssetExportSessionStatusFailed");
                if (completion) {
                    completion(nil, NO);
                }
                break;
            case AVAssetExportSessionStatusExporting:
                LKLog(@"AVAssetExportSessionStatusExporting");
            case AVAssetExportSessionStatusWaiting:
                LKLog(@"AVAssetExportSessionStatusWaiting");
            case AVAssetExportSessionStatusUnknown:
                LKLog(@"AVAssetExportSessionStatusWaiting");
                if (completion) {
                    completion(nil, NO);
                }
                break;
            case AVAssetExportSessionStatusCompleted:
                LKLog(@"AVAssetExportSessionStatusCompleted");
                
                LKLog(@"压缩后大小：%f", outputVideoURL.videoSize);
                if (completion) {
                    completion(outputVideoURL, YES);
                }
                break;
                
            default:
                if (completion) {
                    completion(nil, YES);
                }
                break;
        }
    }];
}

/**
 获取视频的大小，单位（M）
 必须是视频的 URL 方法调出属性

 @return 视频大小
 */
- (CGFloat)videoSize
{
    NSString *path = self.path;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    CGFloat fileSize = -1.0;
    
    if ([fileManager fileExistsAtPath:path])
    {
        NSDictionary *fileDict = [fileManager attributesOfItemAtPath:path error:nil];
        unsigned long long size = [[fileDict objectForKey:NSFileSize] longLongValue];
        fileSize = size * 1.0 / (1024 * 1024);
    }
    else
    {
        NSAssert(true, @"未找到视频文件");
        return 0;
    }
    return fileSize;
}

/**
 获取视频时长, 单位（秒）

 @return 视频时长
 */
- (NSUInteger)videoLength
{
    AVURLAsset *avUrl = [AVURLAsset assetWithURL:self];
    CMTime time = [avUrl duration];
    NSUInteger second = ceil(time.value/time.timescale);
    return second;
}

@end
